package com.producer.utils;

import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import xiaohua.utils.DateUtil;
import xiaohua.utils.exception.AppBusinessException;
import xiaohua.utils.json.JacksonUtil;
import xiaohua.utils.model.Constant;
import xiaohua.utils.model.FieldsDto;

import javax.persistence.Column;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 重写 org.springframework.beans.BeanUtils 的 copyProperties(Object source, Object target) 方法
 * 从model复制属性到pojo中时,model中为null的属性不复制pojo中
 *
 * @author Liunh
 */
@Slf4j
public class BeanUtil extends org.springframework.beans.BeanUtils {

    /**
     * 将实体对象转换为以属性名为key，属性值为value的Map
     *
     * @param obj 实体对象
     * @return Map<String, Object> 属性名和属性值的映射
     */
    public static Map<String, Object> convertEntityToMap(Object obj) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            // 获取对象的Bean信息
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            // 获取所有属性描述器
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String propertyName = descriptor.getName();
                // 跳过class属性（默认会有一个"class"属性）
                if (!"class".equals(propertyName)) {
                    Object value = descriptor.getReadMethod().invoke(obj);
                    map.put(propertyName, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static boolean isFieldExist(Object obj, String fieldName) {
        try {
            obj.getClass().getDeclaredField(fieldName);
            return true;
        } catch (NoSuchFieldException e) {
            try {
                obj.getClass().getSuperclass().getDeclaredField(fieldName);
                return true;
            } catch (NoSuchFieldException e1) {
                return false;
            }
        }
    }

    public static boolean isFieldExist(Class<?> clazz, String fieldName) {
        try {
            clazz.getDeclaredField(fieldName);
            return true;
        } catch (NoSuchFieldException e) {
            try {
                clazz.getSuperclass().getDeclaredField(fieldName);
                return true;
            } catch (NoSuchFieldException e1) {
                return false;
            }
        }
    }

    /**
     * 通过反射为字符串对象的 value 字段重新赋值为 strValue，
     * 从而保证不修改字符串对象的引用，并且能够修改字符串的取值
     * 由于 JDK 8 中有关反射相关的功能自从 JDK 9 开始就已经被限制了，所以要能够使用运行此方法，
     * 需要在运行项目时，添加虚拟机(VM)选项：--add-opens java.base/java.lang=ALL-UNNAMED
     * 开启默认不被允许的行为
     *
     * @param str      需要进行重新赋值的字符串对象
     * @param strValue 要赋值给字符串对象的值
     */
    public static void setFieldStringValue(String str, String strValue) throws NoSuchFieldException, IllegalAccessException {
        // 获取字符串的 value 字段
        final Field field = getField(str, strValue);
        field.setAccessible(Boolean.TRUE);
        // 为字符串对象的 value 字段重新赋值
        // strValueField.set(str, strValue.getBytes(StandardCharsets.UTF_8)); 不要使用该种方法，会出现乱码
        // 采用如下方式，获取 strValue 的 value 字段值，将其赋值给 str 的 value 字段
        field.set(str, field.get(strValue));
    }

    public static void setFieldStringValue(Object obj, String fieldName, String strValue) throws IllegalAccessException {
        final Field field = getField(obj, fieldName);
        if (field != null) {
            field.setAccessible(Boolean.TRUE);
            final Object fieldVal = field.get(fieldName);
            if (fieldVal == null) {
                field.set(obj, strValue);
            }
        }
    }

    public static void setFieldStringValue(Class<?> clazz, String fieldName, String strValue) throws IllegalAccessException {
        final Field field = getField(clazz, fieldName);
        if (field != null) {
            field.setAccessible(Boolean.TRUE);
            final Object fieldVal = field.get(fieldName);
            if (fieldVal == null) {
                field.set(clazz, strValue);
            }
        }
    }

    /**
     * 获取指定对象中的指定字段(不包含父类中的字段)。
     * 此方法在获取指定对象中的指定字段时，会包证获取的指定字段能够被访问。
     *
     * @param obj       要获取字段的指定对象
     * @param fieldName 要获取的指定字段的名称
     * @return 指定对象中的指定字段
     */
    public static Field getField(Object obj, String fieldName) {
        Field field = null;
        try {
            field = obj.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            try {
                field = obj.getClass().getSuperclass().getDeclaredField(fieldName);
            } catch (NoSuchFieldException e1) {
                log.warn(">>>>>> 获取 {} 为空！", fieldName);
            }
        }
        if (field != null) {
            field.setAccessible(Boolean.TRUE);
        }
        return field;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Field field = null;
        try {
            field = clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            try {
                field = clazz.getSuperclass().getDeclaredField(fieldName);
            } catch (NoSuchFieldException e1) {
                log.warn(">>>>>> 获取 {} 为空！", fieldName);
            }
        }
        if (field != null) {
            field.setAccessible(Boolean.TRUE);
        }
        return field;
    }

    public static <T> Set<String> getEntityFields(Class<T> clazz) {
        final Field[] fields = clazz.getDeclaredFields();
        final Set<String> fieldsSet = new HashSet<>();
        Arrays.stream(fields).filter(field -> !"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")).forEach(field -> fieldsSet.add(field.getName()));
        return fieldsSet;
    }

    public static Map<String, Object> getEntityFieldNameAndValue(Object req) {
        final Map<String, Object> fieldNameAndValueMap = new HashMap<>();
        try {
            final Field[] fields = req.getClass().getDeclaredFields();
            Column column;
            String fieldName;
            Object fieldVal;
            for (Field field : fields) {
                if (!"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")) {
                    field.setAccessible(Boolean.TRUE);
                    column = field.getAnnotation(Column.class);
                    fieldName = field.getName();
                    if (column != null) {
                        fieldName = column.name();
                    }
                    fieldVal = field.get(req);
                    if (fieldVal != null) {
                        fieldNameAndValueMap.put(fieldName, fieldVal);
                    }
                }
            }
        } catch (Exception e) {
            log.error(">>>>>> 获取实体属性值异常！!", e);
            throw new AppBusinessException("获取实体属性值异常！", e.getCause());
        }
        return fieldNameAndValueMap;
    }

    public static <T> LinkedHashMap<String, String> getEntityFieldNameAndFieldDesc(Class<T> clazz) {
        final LinkedHashMap<String, String> fieldsMap = new LinkedHashMap<>();
        final Field[] fields = clazz.getDeclaredFields();
        if (fields.length > 0) {
            ApiModelProperty property;
            for (Field field : fields) {
                if (!"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")) {
                    property = field.getAnnotation(ApiModelProperty.class);
                    if (property != null) {
                        fieldsMap.put(field.getName(), property.value());
                    }
                }
            }
        }
        return fieldsMap;
    }

    public static <T> LinkedList<FieldsDto> getFieldNameAndFieldDesc(Class<T> clazz) {
        final LinkedList<FieldsDto> entityFields = new LinkedList<>();
        final Field[] fields = clazz.getDeclaredFields();
        if (fields.length > 0) {
            ApiModelProperty property;
            for (Field field : fields) {
                if (!"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")) {
                    property = field.getAnnotation(ApiModelProperty.class);
                    if (property != null) {
                        entityFields.add(new FieldsDto(field.getName(), property.value()));
                    }
                }
            }
        }
        return entityFields;
    }

    public static <T> Map<String, Type> getEntityFieldsNameAndType(Class<T> clazz) {
        final Field[] fields = clazz.getDeclaredFields();
        final Map<String, Type> fieldsMap = new HashMap<>();
        Class<?> type;
        String typeName;
        for (Field field : fields) {
            if (!"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")) {
                type = field.getType();
                typeName = type.getName();
                if (typeName.toUpperCase(Locale.ROOT).contains("BOOLEAN")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.BOOLEAN);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("BYTE")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.BYTE);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("INT")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.INTEGER);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("LONG")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.LONG);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("STRING")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.STRING);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("DATE")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.DATE);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("TIMESTAMP")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.TIMESTAMP);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("DOUBLE")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.DOUBLE);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("FLOAT")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.FLOAT);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("SHORT")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.SHORT);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("DECIMAL")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.BIG_DECIMAL);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("TEXT")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.TEXT);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("BLOB")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.BLOB);
                }
                if (typeName.toUpperCase(Locale.ROOT).contains("CLOB")) {
                    fieldsMap.put("\"" + field.getName() + "\"", StandardBasicTypes.CLOB);
                }
            }
        }
        return fieldsMap;
    }

    /**
     * 转化为List<T>
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> parseArray(Object data, Class<T> clazz) {
        final String jsonString = JacksonUtil.beanToJson(data);
        return JacksonUtil.jsonToList(jsonString, clazz);
    }

    /**
     * 转化为T
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(Object data, Class<T> clazz) {
        final String jsonString = JacksonUtil.beanToJson(data);
        return JacksonUtil.jsonToBean(jsonString, clazz);
    }

    /**
     * 转化为T
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(Object data, Class<T> clazz, String pattern) {
        final String jsonString = JacksonUtil.beanToJson(data, pattern);
        return JacksonUtil.jsonToBean(jsonString, clazz);
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来
     * 不复制null，但复制空白字符窜""
     * s
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static Object copyProperties1(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, false, (String[]) null);
        return target;
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来
     * 不复制null，但复制空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyProperties(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, false, (String[]) null);
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来
     * 不复制null，但复制空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
        copyProperties(source, target, null, false, ignoreProperties);
    }

    /**
     * 不复制null和空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyExcludeNullAndEmpty(Object source, Object target, String... ignoreProperties) throws BeansException {
        copyProperties(source, target, null, true, ignoreProperties);
    }

    /**
     * 不复制null和空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyPropertiesExcludeNullAndEmpty(Object source, Object target, String... ignoreProperties) throws BeansException {
        copyProperties(source, target, null, true, ignoreProperties);
    }

    /**
     * 不复制null和空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyExcludeNullAndEmpty(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, true, (String[]) null);
    }

    /**
     * 不复制null和空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyPropertiesExcludeNullAndEmpty(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, true, (String[]) null);
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来,修改部分代码
     *
     * @param source
     * @param target
     * @param editable
     * @param emptyExclude     排除空白字符窜
     * @param ignoreProperties
     * @throws BeansException
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, boolean emptyExclude, String... ignoreProperties) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }
        final PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        final List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
        Method writeMethod;
        PropertyDescriptor sourcePd;
        Method readMethod;
        Object value;
        Class<?>[] writeParameterTypes;
        Class<?> returnType;
        for (PropertyDescriptor targetPd : targetPds) {
            writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
                sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    readMethod = sourcePd.getReadMethod();
                    //if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                    if (readMethod != null) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            value = readMethod.invoke(source);
                            // 判断被复制的属性是否为null, 如果不为null才复制
                            if (value != null) {
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                } else if (value instanceof List && emptyExclude && ((List<?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof Set && emptyExclude && ((Set<?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof Map && emptyExclude && ((Map<?, ?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof String && emptyExclude && StringUtils.isBlank(String.valueOf(value))) {
                                    continue;
                                } else {
                                    writeParameterTypes = writeMethod.getParameterTypes();
                                    returnType = readMethod.getReturnType();
                                    if (!returnType.getName().equals(writeParameterTypes[0].getName()) && writeParameterTypes.length == 1) {
                                        if ((value instanceof Date || returnType.getName().contains("Date")) && writeParameterTypes[0].getName().contains("String")) {
                                            if (String.valueOf(value).contains("-") && String.valueOf(value).length() == 10) {
                                                value = xiaohua.utils.DateUtil.date2Str((Date) value, xiaohua.utils.DateUtil.DATE_FORMAT_DAY_PATTERN);
                                            } else {
                                                value = xiaohua.utils.DateUtil.date2Str((Date) value, xiaohua.utils.DateUtil.DATE_FORMAT_DEFAULT);
                                            }
                                        }
                                        if ((value instanceof String || returnType.getName().contains("String")) && writeParameterTypes[0].getName().contains("Date")) {
                                            if (String.valueOf(value).contains("-") && String.valueOf(value).length() == 10) {
                                                value = xiaohua.utils.DateUtil.str2Date(String.valueOf(value), xiaohua.utils.DateUtil.DATE_FORMAT_DAY_PATTERN);
                                            } else {
                                                if (value != null && StringUtils.isBlank(String.valueOf(value))) {
                                                    continue;
                                                }
                                                if (String.valueOf(value).matches(Constant.REGEXP_NUMBER)) {
                                                    value = xiaohua.utils.DateUtil.parse(Long.parseLong(String.valueOf(value)));
                                                } else {
                                                    value = xiaohua.utils.DateUtil.str2Date(String.valueOf(value), DateUtil.DATE_FORMAT_DEFAULT);
                                                }
                                            }
                                        }
                                    }
                                }
                                writeMethod.invoke(target, value);
                            }
                        } catch (Throwable ex) {
                            throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }
    }

}
